package com.jxpanda.spring.module.auth.endpoint;

import com.jxpanda.spring.module.auth.core.authentication.strategy.*;
import com.jxpanda.spring.module.auth.core.user.OAuth2ReactiveUserDetailsRepository;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.security.oauth2.core.AuthorizationGrantType;

import java.util.function.Function;

/**
 * 由于要扩展自定义的grant_type，所以写一个枚举
 */
@RequiredArgsConstructor
public enum GrantType {

    /**
     * 以下是标准oauth2规范支持的grant_type
     */
    AUTHORIZATION_CODE("authorization_code", OAuth2Request::getCode),
    /**
     * oauth2规范已经废弃，不推荐使用
     */
    PASSWORD("password", OAuth2Request::getPassword),
    CLIENT_CREDENTIALS("client_credentials", OAuth2Request::getClientSecret),
    REFRESH_TOKEN("refresh_token", OAuth2Request::getRefreshToken),
    /**
     * 以下是自定义的
     * 用于手机号/邮箱的验证码登录
     */
    PHONE_CAPTCHA("phone_captcha", OAuth2Request::getCaptcha),
    EMAIL_CAPTCHA("email_captcha", OAuth2Request::getCaptcha),
    /**
     * 微信公众号登录
     */
    WECHAT_OPEN_PLATFORM("wechat_open_platform", OAuth2Request::getCode),
    /**
     * 微信小程序登录
     */
    WECHAT_MINI_PROGRAM("wechat_mini_program", OAuth2Request::getCode);

    @Getter
    private final String value;

    private final Function<OAuth2Request, String> credentialFunction;

    public String getCredential(OAuth2Request request) {
        return credentialFunction.apply(request);
    }

    public AuthorizationGrantType toAuthorizationGrantType() {
        return new AuthorizationGrantType(value);
    }

    public static GrantType of(String value) {
        for (GrantType grantType : values()) {
            if (grantType.getValue().equals(value)) {
                return grantType;
            }
        }
        throw new IllegalArgumentException("不支持的授权类型：" + value);
    }

}
